package com.gh.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.reggie.common.R;
import com.gh.reggie.dto.DishDto;
import com.gh.reggie.entity.Category;
import com.gh.reggie.entity.Dish;
import com.gh.reggie.entity.DishFlavor;
import com.gh.reggie.service.CategoryService;
import com.gh.reggie.service.DishFlavorService;
import com.gh.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    /**
     * 查询菜品页面(多表：dish,category)
     * category:categoryName
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page (int page,int pageSize,String name){
        //构建分页构造器对象，将需要分页的条件传入，对Dish数据List分页
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> pageDishDtoInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件(更新时间)
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //先将基本的dish数据查到再加工
        dishService.page(pageInfo,queryWrapper);
        //开始加工，抽取records列表
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            //将没有分类名，但是具有其他菜品字段数据的列表复制，其实就是保留dish列表，然后多加几条属性，应为dto继承并拓展了dish
            BeanUtils.copyProperties(item,dishDto);
            //获取dish中的分类id(categoryId)
            Long categoryId = item.getCategoryId();
            //根据id查询分类名(categoryName)
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将records列表更新就行了,但由于page泛化对象为dish,传递dishdto对象的list就不行
        //那么创建按一个新的page，将除了records的所有属性拷贝,（被拷贝对象，拷贝对象名，忽略属性）
        BeanUtils.copyProperties(pageInfo,pageDishDtoInfo,"records");
        //更新records
        pageDishDtoInfo.setRecords(list);


        return R.success(pageDishDtoInfo);
    }


    /**
     * 根据菜品查询菜品表和口味（多表：dish,dishFlavor）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> dishDto(@PathVariable Long id){

        DishDto dishDto = dishService.getDishDtoById(id);

        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);
        return R.success("更新菜品成功");
    }


    /**
     * 新增套餐时根据，查询对应种类菜品数据(查对应种类的菜品)
     * @param dish
     * @return
     */
/*    @GetMapping("list")
    public R<List<Dish>> list (Dish dish){

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //CategoryId not null and CategoryId = ?
        queryWrapper.eq( dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //and status = 1
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);

    }*/
    @GetMapping("list")
    public R<List<DishDto>> list (Dish dish){

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //CategoryId not null and CategoryId = ?
        queryWrapper.eq( dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //and status = 1
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category !=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //菜品ID
            Long dishId = item.getId();
            //查口味(select * from dish_flavor where dishId = ?)
            List<DishFlavor> dishFlavorList = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, dishId));
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);

    }


    /**
     * 售卖状态单条变更和批量变更
     * @param param
     * @param id
     * @return
     */
    @PostMapping("/status/{param}")
    public R<String> updateStatus(@PathVariable("param")Integer param,@RequestParam List<Long> id){
        log.info(String.valueOf(param));
        log.info(id.toString());

         //update dish set status = param where id in id
/*        //第一种方法
        ArrayList<Dish> dishes = new ArrayList<>();
        for (Long aLong : id) {
            Dish dish = new Dish();
            dish.setStatus(param);
            dish.setId(aLong);
            dishes.add(dish);
        }
        dishService.updateBatchById(dishes);*/

        //第二种
        dishService.lambdaUpdate().set(Dish::getStatus,param).in(Dish::getId,id).update();

        return R.success("菜品状态变更成功");
    }


    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> id){
        log.info(id.toString());

        dishService.removeWithFlavor(id);

        return R.success("删除菜品成功");
    }

}
